package com.m3958.logcollector.datacommons.util;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.repository.support.Repositories;
import org.springframework.data.rest.core.mapping.ResourceMappings;
import org.springframework.data.rest.core.mapping.ResourceMetadata;

/**
 * @author jianglibo@gmail.com
 *         2015年9月13日
 */

public class RepoUtils {

    public static Object findRepoByPath(Repositories repositories, ResourceMappings resourceMappings, String path) {
        for (Class<?> domainType : repositories) {
            ResourceMetadata mapping = resourceMappings.getMetadataFor(domainType);
            if (mapping.getPath().matches(path)) {
                return repositories.getRepositoryFor(domainType);
            }
        }
        return null;
    }

    public static Pageable addSortToPageableIfNoSort(Pageable pageable) {
        return addSortToPageableIfNoSort(pageable, "-createdAt");
    }

    public static Pageable addSortToPageableIfNoSort(Pageable pageable, String sort) {
        Sort st;
        if (sort.startsWith("-")) {
            st = new Sort(Direction.DESC, sort.substring(1));
        } else if (sort.startsWith("+")) {
            st = new Sort(Direction.ASC, sort.substring(1));
        } else {
            st = new Sort(Direction.ASC, sort);
        }
        return addSortToPageableIfNoSort(pageable, st);
    }
    
    public static Pageable addSortToPageableIfNoSort(Pageable pageable, Sort sort) {
        return new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
    }

    public static Pageable createPageable(int page, int size, Sort sort) {
        return new PageRequest(page, size, sort);
    }

    public static Pageable createPageable(int size, Sort sort) {
        return new PageRequest(0, size, sort);
    }

    public static Pageable createPageable(int size) {
        return new PageRequest(0, size, new Sort(Direction.ASC, "createdAt"));
    }

}
